package com.ppgames.gm.gmsystem.auth;


import com.ppgames.gm.gmsystem.GmCore;
import com.ppgames.gm.gmsystem.util.JsonHelper;

import java.util.concurrent.locks.ReentrantLock;

public class CacheManager {

    private static ReentrantLock tokenLock = new ReentrantLock();

    public static void addToken(OptInfo optInfo) {
        tokenLock.lock();
        removeTokenByAccountCode(optInfo.getAccountCode());
        GmCore.TOKEN_CACHE.put(GmCore.Constant.TOKEN_ID_REL_FLAG + optInfo.getAccountCode(), optInfo.getToken());
        GmCore.TOKEN_CACHE.put(GmCore.Constant.TOKEN_INFO_FLAG + optInfo.getToken(), JsonHelper.toJsonString(optInfo));
        tokenLock.unlock();
    }

    public static void removeTokenByAccountCode(String accountCode) {
        String token = getToken(accountCode);
        if (token != null) {
            removeToken(token);
        }
    }

    public static void removeToken(String token) {
        OptInfo tokenInfo = getTokenInfo(token);
        if (tokenInfo != null) {
            GmCore.TOKEN_CACHE.remove(GmCore.Constant.TOKEN_ID_REL_FLAG + tokenInfo.getAccountCode());
            GmCore.TOKEN_CACHE.remove(GmCore.Constant.TOKEN_INFO_FLAG + token);
        }
    }

    public static String getToken(String accountCode) {
        return GmCore.TOKEN_CACHE.get(GmCore.Constant.TOKEN_ID_REL_FLAG + accountCode);
    }

    public static OptInfo getTokenInfo(String token) {
        return JsonHelper.toObject(GmCore.TOKEN_CACHE.get(GmCore.Constant.TOKEN_INFO_FLAG + token), OptInfo.class);
    }


}
